// 明显的肉鸽系统 - 立即可见的效果
(function() {
    'use strict';
    
    class VisibleRoguelikeSystem {
        constructor() {
            this.active = false;
            this.runCount = parseInt(localStorage.getItem('visibleRogue_runCount') || '0');
            this.currentUpgrades = [];
            this.equipmentDropped = 0;
            
            // 立即启动
            this.initialize();
        }
        
        initialize() {
            console.log('🎮 明显肉鸽系统启动！');
            
            // 立即显示欢迎界面
            this.showWelcomeScreen();
            
            // 立即开始监控
            this.startImmediate();
            
            this.active = true;
        }
        
        showWelcomeScreen() {
            const welcomeDiv = document.createElement('div');
            welcomeDiv.id = 'roguelikeWelcome';
            welcomeDiv.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: rgba(0, 0, 0, 0.9); z-index: 20000;
                display: flex; align-items: center; justify-content: center;
                color: white; font-family: monospace;
            `;
            
            welcomeDiv.innerHTML = `
                <div style="text-align: center; max-width: 600px; padding: 40px; background: rgba(30, 30, 30, 0.95); border-radius: 15px; border: 3px solid #00ff88;">
                    <h1 style="color: #00ff88; font-size: 36px; margin-bottom: 20px;">🎲 肉鸽模式已激活！</h1>
                    <p style="font-size: 18px; line-height: 1.6; margin-bottom: 20px;">
                        欢迎来到增强的肉鸽体验！<br>
                        • 每次游戏都有随机装备掉落<br>
                        • 关卡完成后选择强力升级<br>
                        • 死亡后获得永久进度奖励<br>
                        • 当前轮次: ${this.runCount + 1}
                    </p>
                    <button id="startRoguelike" style="
                        background: linear-gradient(45deg, #00ff88, #00aa55);
                        border: none; color: white; padding: 15px 30px;
                        font-size: 18px; border-radius: 8px; cursor: pointer;
                        font-weight: bold; text-transform: uppercase;
                    ">开始肉鸽冒险！</button>
                </div>
            `;
            
            document.body.appendChild(welcomeDiv);
            
            document.getElementById('startRoguelike').addEventListener('click', () => {
                welcomeDiv.style.animation = 'fadeOut 0.5s ease-out';
                setTimeout(() => {
                    if (welcomeDiv.parentNode) {
                        document.body.removeChild(welcomeDiv);
                    }
                }, 500);
                this.startNewRun();
            });
            
            // 添加动画样式
            this.addWelcomeStyles();
        }
        
        addWelcomeStyles() {
            if (document.getElementById('welcomeStyles')) return;
            
            const styles = document.createElement('style');
            styles.id = 'welcomeStyles';
            styles.textContent = `
                @keyframes fadeOut {
                    from { opacity: 1; }
                    to { opacity: 0; }
                }
                
                #startRoguelike:hover {
                    background: linear-gradient(45deg, #00aa55, #007733) !important;
                    transform: translateY(-2px);
                    box-shadow: 0 5px 15px rgba(0, 255, 136, 0.3);
                }
            `;
            document.head.appendChild(styles);
        }
        
        startNewRun() {
            this.runCount++;
            localStorage.setItem('visibleRogue_runCount', this.runCount.toString());
            this.currentUpgrades = [];
            this.equipmentDropped = 0;
            
            // 立即显示肉鸽HUD
            this.createRoguelikeHUD();
            
            // 立即开始掉落装备
            this.immediateEquipmentDrop();
            
            // 立即监控游戏状态
            this.startGameMonitoring();
            
            console.log(`🎯 开始第 ${this.runCount} 轮肉鸽游戏`);
        }
        
        createRoguelikeHUD() {
            // 移除旧的HUD
            const oldHUD = document.getElementById('roguelikeHUD');
            if (oldHUD) oldHUD.remove();
            
            const hud = document.createElement('div');
            hud.id = 'roguelikeHUD';
            hud.style.cssText = `
                position: fixed; top: 10px; left: 10px; z-index: 10000;
                background: linear-gradient(135deg, rgba(0, 0, 0, 0.8), rgba(30, 30, 30, 0.8));
                border: 2px solid #00ff88; border-radius: 10px; padding: 15px;
                color: white; font-family: monospace; font-size: 14px;
                min-width: 200px; backdrop-filter: blur(5px);
            `;
            
            hud.innerHTML = `
                <div style="color: #00ff88; font-weight: bold; margin-bottom: 10px;">🎲 肉鸽状态</div>
                <div>轮次: <span id="runDisplay">${this.runCount}</span></div>
                <div>升级: <span id="upgradeDisplay">0</span></div>
                <div>装备: <span id="equipmentDisplay">0</span></div>
                <div id="rogueStatus" style="margin-top: 10px; color: #ffff00;">准备就绪</div>
            `;
            
            document.body.appendChild(hud);
        }
        
        updateHUD(status) {
            const statusEl = document.getElementById('rogueStatus');
            const upgradeEl = document.getElementById('upgradeDisplay');
            const equipmentEl = document.getElementById('equipmentDisplay');
            
            if (statusEl) statusEl.textContent = status;
            if (upgradeEl) upgradeEl.textContent = this.currentUpgrades.length;
            if (equipmentEl) equipmentEl.textContent = this.equipmentDropped;
        }
        
        immediateEquipmentDrop() {
            // 游戏开始5秒后立即掉落装备
            setTimeout(() => {
                this.dropVisibleEquipment();
            }, 5000);
            
            // 之后每15秒掉落一次
            setInterval(() => {
                if (this.isGamePlaying()) {
                    this.dropVisibleEquipment();
                }
            }, 15000);
        }
        
        dropVisibleEquipment() {
            try {
                if (!window.gameEngine || !window.gameEngine.powerUps) return;
                
                this.equipmentDropped++;
                
                const rarities = ['common', 'rare', 'epic', 'legendary'];
                const rarity = rarities[Math.floor(Math.random() * rarities.length)];
                
                const colors = {
                    common: '#ffffff',
                    rare: '#0088ff',
                    epic: '#aa00ff',
                    legendary: '#ffaa00'
                };
                
                const equipment = {
                    x: Math.random() * 700 + 150,
                    y: Math.random() * 500 + 150,
                    width: 30,
                    height: 30,
                    type: 'roguelike_equipment',
                    rarity: rarity,
                    color: colors[rarity],
                    name: `${rarity} 装备`,
                    collected: false,
                    glowEffect: true,
                    dropTime: Date.now()
                };
                
                window.gameEngine.powerUps.push(equipment);
                
                // 显明显的掉落特效
                this.showDropEffect(equipment.x, equipment.y, rarity);
                
                // 更新HUD
                this.updateHUD(`掉落 ${rarity} 装备！`);
                
                console.log(`📦 掉落可见装备: ${rarity} at (${equipment.x}, ${equipment.y})`);
                
            } catch (error) {
                console.error('装备掉落失败:', error);
            }
        }
        
        showDropEffect(x, y, rarity) {
            const effect = document.createElement('div');
            effect.style.cssText = `
                position: fixed; left: ${x}px; top: ${y}px;
                width: 50px; height: 50px; z-index: 9999;
                background: radial-gradient(circle, rgba(255, 255, 255, 0.8), transparent);
                border-radius: 50%; pointer-events: none;
                animation: dropGlow 2s ease-out;
            `;
            
            document.body.appendChild(effect);
            
            setTimeout(() => {
                if (effect.parentNode) {
                    document.body.removeChild(effect);
                }
            }, 2000);
            
            // 添加文字提示
            this.showFloatingText(`${rarity.toUpperCase()} 装备掉落！`, x, y);
        }
        
        showFloatingText(text, x, y) {
            const textEl = document.createElement('div');
            textEl.style.cssText = `
                position: fixed; left: ${x}px; top: ${y - 30}px;
                color: #00ff88; font-weight: bold; font-size: 16px;
                z-index: 9999; pointer-events: none; font-family: monospace;
                text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
                animation: floatUp 3s ease-out;
            `;
            textEl.textContent = text;
            
            document.body.appendChild(textEl);
            
            setTimeout(() => {
                if (textEl.parentNode) {
                    document.body.removeChild(textEl);
                }
            }, 3000);
            
            // 添加动画样式
            this.addFloatingStyles();
        }
        
        addFloatingStyles() {
            if (document.getElementById('floatingStyles')) return;
            
            const styles = document.createElement('style');
            styles.id = 'floatingStyles';
            styles.textContent = `
                @keyframes dropGlow {
                    0% { 
                        transform: scale(0.5);
                        opacity: 1;
                    }
                    50% {
                        transform: scale(1.2);
                        opacity: 0.8;
                    }
                    100% { 
                        transform: scale(1);
                        opacity: 0;
                    }
                }
                
                @keyframes floatUp {
                    0% { 
                        opacity: 1;
                        transform: translateY(0);
                    }
                    100% { 
                        opacity: 0;
                        transform: translateY(-50px);
                    }
                }
            `;
            document.head.appendChild(styles);
        }
        
        startGameMonitoring() {
            let lastLevel = 0;
            let lastGameState = '';
            
            setInterval(() => {
                try {
                    const currentLevel = window.levelManager ? window.levelManager.currentLevel : 0;
                    const gameState = window.gameEngine ? window.gameEngine.gameState : '';
                    
                    // 检测关卡完成
                    if (gameState === 'levelComplete' && lastGameState !== 'levelComplete') {
                        this.onLevelComplete(currentLevel);
                    }
                    
                    // 检测关卡变化
                    if (currentLevel > lastLevel && currentLevel > 0) {
                        this.onLevelStart(currentLevel);
                        lastLevel = currentLevel;
                    }
                    
                    // 检测游戏结束
                    if (gameState === 'gameOver' && lastGameState !== 'gameOver') {
                        this.onGameOver();
                    }
                    
                    lastGameState = gameState;
                    
                } catch (error) {
                    console.error('监控错误:', error);
                }
            }, 1000);
        }
        
        onLevelStart(level) {
            this.updateHUD(`进入关卡 ${level}`);
            
            // 显示关卡开始特效
            this.showBigNotification(`🎯 关卡 ${level} 开始`, '寻找装备和升级！');
            
            // 立即掉落一个装备
            setTimeout(() => {
                this.dropVisibleEquipment();
            }, 3000);
            
            console.log(`🎯 关卡 ${level} 开始 - 肉鸽增强激活`);
        }
        
        onLevelComplete(level) {
            this.updateHUD(`关卡 ${level} 完成！`);
            
            // 显示升级选择
            setTimeout(() => {
                this.showUpgradeSelection();
            }, 2000);
            
            console.log(`🏆 关卡 ${level} 完成 - 准备升级选择`);
        }
        
        showUpgradeSelection() {
            // 强制显示升级选择界面
            if (window.roguelikeSystem && window.roguelikeSystem.showUpgradeSelection) {
                try {
                    window.roguelikeSystem.showUpgradeSelection();
                } catch (error) {
                    // 如果原系统失败，显示自定义升级
                    this.showCustomUpgradeSelection();
                }
            } else {
                this.showCustomUpgradeSelection();
            }
        }
        
        showCustomUpgradeSelection() {
            const upgradeMenu = document.createElement('div');
            upgradeMenu.id = 'customUpgradeMenu';
            upgradeMenu.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: rgba(0, 0, 0, 0.9); z-index: 15000;
                display: flex; align-items: center; justify-content: center;
            `;
            
            const upgrades = [
                { name: '伤害提升', desc: '武器伤害增加50%', icon: '⚔️' },
                { name: '生命增强', desc: '最大生命值增加30%', icon: '❤️' },
                { name: '速度提升', desc: '移动速度增加40%', icon: '💨' }
            ];
            
            upgradeMenu.innerHTML = `
                <div style="background: rgba(20, 20, 20, 0.95); padding: 40px; border-radius: 15px; border: 3px solid #00ff88; text-align: center; max-width: 800px;">
                    <h2 style="color: #00ff88; font-size: 32px; margin-bottom: 30px;">🎲 选择你的升级</h2>
                    <div style="display: flex; gap: 20px; justify-content: center;">
                        ${upgrades.map((upgrade, index) => `
                            <div class="upgrade-option" data-index="${index}" style="
                                background: rgba(40, 40, 40, 0.9); border: 2px solid #666;
                                border-radius: 10px; padding: 20px; cursor: pointer;
                                color: white; text-align: center; width: 200px;
                                transition: all 0.3s ease;
                            ">
                                <div style="font-size: 48px; margin-bottom: 10px;">${upgrade.icon}</div>
                                <h3 style="color: #00ff88; margin-bottom: 10px;">${upgrade.name}</h3>
                                <p style="color: #ccc; font-size: 14px;">${upgrade.desc}</p>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
            
            document.body.appendChild(upgradeMenu);
            
            // 添加点击事件
            upgradeMenu.querySelectorAll('.upgrade-option').forEach((option, index) => {
                option.addEventListener('click', () => {
                    this.selectUpgrade(upgrades[index]);
                    upgradeMenu.style.animation = 'fadeOut 0.5s ease-out';
                    setTimeout(() => {
                        if (upgradeMenu.parentNode) {
                            document.body.removeChild(upgradeMenu);
                        }
                    }, 500);
                });
                
                option.addEventListener('mouseenter', () => {
                    option.style.borderColor = '#00ff88';
                    option.style.transform = 'translateY(-5px)';
                });
                
                option.addEventListener('mouseleave', () => {
                    option.style.borderColor = '#666';
                    option.style.transform = 'translateY(0)';
                });
            });
        }
        
        selectUpgrade(upgrade) {
            this.currentUpgrades.push(upgrade);
            
            // 应用升级效果
            try {
                if (upgrade.name === '伤害提升' && window.player && window.player.currentWeapon) {
                    window.player.currentWeapon.damage = Math.floor(window.player.currentWeapon.damage * 1.5);
                } else if (upgrade.name === '生命增强' && window.player) {
                    window.player.maxHealth = Math.floor(window.player.maxHealth * 1.3);
                    window.player.health = window.player.maxHealth;
                    if (window.player.updateHealthUI) window.player.updateHealthUI();
                } else if (upgrade.name === '速度提升' && window.player) {
                    window.player.speed *= 1.4;
                }
            } catch (error) {
                console.error('升级应用失败:', error);
            }
            
            // 显示获得升级的特效
            this.showBigNotification(`🎉 获得升级！`, upgrade.name);
            this.updateHUD(`获得: ${upgrade.name}`);
            
            console.log(`✨ 选择升级: ${upgrade.name}`);
        }
        
        onGameOver() {
            this.updateHUD('游戏结束');
            
            // 显示死亡总结
            this.showDeathSummary();
            
            console.log('💀 游戏结束 - 显示肉鸽总结');
        }
        
        showDeathSummary() {
            setTimeout(() => {
                this.showBigNotification(
                    `💀 第 ${this.runCount} 轮结束`,
                    `获得了 ${this.currentUpgrades.length} 个升级\n掉落了 ${this.equipmentDropped} 个装备`,
                    5000
                );
                
                // 5秒后自动开始新轮次
                setTimeout(() => {
                    this.showWelcomeScreen();
                }, 5000);
            }, 2000);
        }
        
        showBigNotification(title, message, duration = 3000) {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed; top: 50%; left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0, 0, 0, 0.9); color: white;
                padding: 30px 40px; border-radius: 15px;
                border: 3px solid #00ff88; z-index: 12000;
                text-align: center; font-family: monospace;
                animation: bigNotifyIn 0.5s ease-out;
            `;
            
            notification.innerHTML = `
                <h2 style="color: #00ff88; font-size: 28px; margin-bottom: 15px;">${title}</h2>
                <p style="font-size: 16px; line-height: 1.4; white-space: pre-line;">${message}</p>
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.animation = 'bigNotifyOut 0.5s ease-in';
                setTimeout(() => {
                    if (notification.parentNode) {
                        document.body.removeChild(notification);
                    }
                }, 500);
            }, duration);
            
            this.addBigNotificationStyles();
        }
        
        addBigNotificationStyles() {
            if (document.getElementById('bigNotifyStyles')) return;
            
            const styles = document.createElement('style');
            styles.id = 'bigNotifyStyles';
            styles.textContent = `
                @keyframes bigNotifyIn {
                    0% { 
                        opacity: 0;
                        transform: translate(-50%, -50%) scale(0.7);
                    }
                    100% { 
                        opacity: 1;
                        transform: translate(-50%, -50%) scale(1);
                    }
                }
                
                @keyframes bigNotifyOut {
                    0% { 
                        opacity: 1;
                        transform: translate(-50%, -50%) scale(1);
                    }
                    100% { 
                        opacity: 0;
                        transform: translate(-50%, -50%) scale(0.7);
                    }
                }
            `;
            document.head.appendChild(styles);
        }
        
        isGamePlaying() {
            return window.gameEngine && window.gameEngine.gameState === 'playing';
        }
        
        startImmediate() {
            // 立即开始一些明显的效果
            console.log('🎲 肉鸽系统立即激活 - 效果将很快显现');
            
            // 2秒后显示第一个提示
            setTimeout(() => {
                this.showBigNotification('🎮 肉鸽模式激活', '装备掉落和升级选择已启用！');
            }, 2000);
        }
    }
    
    // 立即启动
    try {
        const visibleRogue = new VisibleRoguelikeSystem();
        window.visibleRoguelikeSystem = visibleRogue;
        console.log('🎯 明显肉鸽系统已加载！');
    } catch (error) {
        console.error('明显肉鸽系统启动失败:', error);
    }
    
})();